// pages/carSuborder/carSuborder.js
var app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    r: 1,//1是购买过来2是选择地址过来
    total:0,
    list:[],
    address: null,
    hasAdr: true,
    payType: 1,//1是余额5是微信
    orderId:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let list = wx.getStorageSync('sublist');//购物提交车列表
    this.setData({ r: options.r });
    let total = 0;
    let self = this;
    console.log(list)
    for (let i in list) {
      total += (list[i].quantity * list[i].vipPrice);
    }
    this.setData({ list: list, total: total });
    //收货地址
    if (options.r == 1) {
      wx.request({
        url: app.globalData.reqPath + 'shop/MembersAddress',
        header: {
          'authorization': app.globalData.authorization
        },
        success: function ({ data, header }) {
          if (data.code == 200) {
            let address = data.data;
            if (address.length == 0) {
              self.setData({ hasAdr: false })
            }else{
                let defualtaddress;
                defualtaddress = address.filter(function (item) {
                  return item.isDefault == 1;
                })

                if (defualtaddress.length == 0) {
                self.setData({hasAdr: true });
                } else {
                  self.setData({ address: defualtaddress[0], hasAdr: true });
                }
            }
          }
        }
      })
    } else {
      wx.request({
        url: app.globalData.reqPath + 'shop/MembersAddress/' + options.adrId,
        header: {
          'authorization': app.globalData.authorization
        },
        success: function ({ data, header }) {

          if (data.code == 200) {
            let address = data.data;

            self.setData({ address: address, hasAdr: true });
          }
        }
      })
    }
    wx.hideShareMenu()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  goaddressList:function(){//去选择地址
    wx.navigateTo({
      url: '/pages/addressList/addressList?r=2',
    })
  },
  changePayway:function(e){
    this.setData({ payType: e.detail.value })
  },
  onClickButton:function(){//提交订单
    if (!this.data.address) {
      wx.showToast({
        title: '请添加地址',
        icon: 'none'
      })
      return false;
    }
    let list = this.data.list;
    let self = this;
    let skuAndNum = [];
    for (let i in list) {
      skuAndNum.push([list[i].skuId, list[i].quantity])
    }
    let data = {
      skuAndNum: JSON.stringify(skuAndNum),
      addressId: this.data.address.id
    }
    console.log(JSON.stringify(data))
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    wx.request({
      url: app.globalData.reqPath + 'shop/orders',
      data: JSON.stringify(data),
      header: {
        'authorization': app.globalData.authorization
      },
      method: 'POST',
      success: function ({ data, header }) {
        console.log(data)
        if (data.code == 200) {
          wx.hideLoading()
          let id = data.data;
          self.setData({ orderId: id })
          if (self.data.payType == 1) {
            
            let userInfo = wx.getStorageSync('userInfo');
            if (userInfo.tradePasswordSet == 0) {
              wx.showModal({
                content: '没有支付密码，去设置',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '/pages/setpaw/setpaw',
                    })
                  }
                }
              })
            } else {
              self.setData({ show: true })
            }

          } else {//微信支付
          
            wx.request({
              url: app.globalData.reqPath + 'shop/OrdersStatusPay',
              method: 'POST',
              header: {
                'authorization': app.globalData.authorization
              },
              data: {
                orderId: id,
                payType: 5,
              },
              success: function ({ data }) {
                console.log(data)
                let wxpaydata = data.data;
                if (data.code == 200) {
                  wx.requestPayment({
                    timeStamp: wxpaydata.timeStamp,
                    nonceStr: wxpaydata.nonceStr,
                    package: wxpaydata.package,
                    signType: wxpaydata.signType,
                    paySign: wxpaydata.paySign,
                    success(res) {
                      console.log(res)
                      if (res.errMsg == "requestPayment:ok") {
                        wx.redirectTo({
                          url: '/pages/order/order?s=2',
                        })
                      }
                    },
                    fail(res) {
                      if (res.errMsg == 'requestPayment:fail cancel') {//res.errMsg //requestPayment: fail cancel //用户取消支付
                        wx.redirectTo({
                          url: '/pages/order/order?s=1',
                        })
                      } else { //requestPayment: fail(detail message)//调用支付失败
                        wx.showToast({
                          title: '支付失败，请重试',
                          icon: 'none'
                        })
                      }
                    }
                  })
                } else {

                }

              }
            })
          }

        }else{
          wx.showToast({
            title: data.data.msg,
            icon:'none'
          })
        }
      }
    })
  },
  comfirmpawPay:function(e){
    let paw = e.detail.value.paw;
    let self = this;
    wx.request({
      url: app.globalData.reqPath + 'shop/OrdersStatusPay',
      data: {
        orderId: this.data.orderId,
        payType: 1,
        tradePassword: paw
      },
      header: {
        'authorization': app.globalData.authorization
      },
      method: 'POST',
      success: function (res) {
        if (res.data.code == 200) {
          wx.showToast({
            title: '支付成功',
          })
          setTimeout(function () {
            wx.redirectTo({
              url: '/pages/order/order?s=2',
            })
          }, 300)

        } else {
          wx.showToast({
            title: res.data.data.msg,
            icon: 'none',
            success: function () {
              self.setData({ show: false })
            }
          })
        }
      }
    })
  }
})